import Cookie from 'js-cookie'
export default {
  state: {
    isCollapse: false,
    dialogVisible: false,
    modelType: 0,
    tableList: [],
    pagelimit: {
      page: 1,
      limit: 10
    },

    total: 0,
    form: {
      name: '',
      age: '',
      sex: '',
      birth: '',
      addr: ''
    },
    menu: [],
    tabList: [
      {
        path: '/home',
        name: 'home',
        label: '首页',
        icon: 's-home',
        url: 'Home/Home'
      }
    ]
  },
  mutations: {
    changemenu(state) {
      state.isCollapse = !state.isCollapse
    },
    selectMenu(state, val) {
      // console.log(val);
      if (val.name !== 'home') {
        const index = state.tabList.findIndex(item => item.name === val.name)
        if (index === -1) {
          state.tabList.push(val)
        }
      }
    },
    removeTagList(state, item) {
      // console.log(item);
      const index = state.tabList.findIndex(val => item.path === val.path)
      state.tabList.splice(index, 1)
    },
    changedialogVisible(state, val) {
      state.dialogVisible = val
    },
    handletable(state) {
      state.modelType = 0
      state.dialogVisible = true
    },
    edittable(state, val) {
      state.modelType = 1
      state.dialogVisible = true
      // 深拷贝
      state.form = JSON.parse(JSON.stringify(val))
    },
    gettableData(state, val) {
      // console.log(val)
      state.tableList = val.list
      state.total = val.count || 0
    },
    setmenu(state, val) {
      state.menu = val
      Cookie.set('menu', JSON.stringify(val))
    },
    addmenu(state, router) {
      if (!Cookie.get('menu')) {
        return
      } else {
        const menu = JSON.parse(Cookie.get('menu'))

        state.menu = menu
        // console.log(state.menu)
        const menuArray = []
        menu.forEach(item => {
          if (item.children) {
            item.children = item.children.map(item => {
              item.component = () => import(`../views/${item.url}`)
              return item
            })
            menuArray.push(...item.children)
          } else {
            item.component = () => import(`../views/${item.url}`)
            menuArray.push(item)
          }
        })
        // console.log(menuArray)
        menuArray.forEach(item => {
          router.addRoute('Main', item)
        })
      }
    }
  }
}
